<?php

namespace App\Http\Controllers\Admin\Administration;

use App\Exports\FixedExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\administration\FixedRequest;
use App\Imports\FixedImport;
use App\Models\administration\FixedModel;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Fixed extends Controller
{
    use FixedRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $user = $request->input('user', '');
        $buy_start = $request->input('buy_start', '');
        $buy_end = $request->input('buy_end', '');

        $query = FixedModel::query()->with('create_admin');

        if($name){
            $query = $query->where('name', 'like', '%'.$name.'%')->orWhere('code', 'like', '%'.$name.'%');
        }

        if($user){
            $query = $query->where('user', 'like', '%'.$user.'%');
        }

        if($buy_start && $buy_end){
            $query = $query->whereBetween('buy_date', [$buy_start, $buy_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'code' => $item->code,
                'name' => $item->name,
                'category' => $item->category,
                'type' => $item->type,
                'spe' => $item->spe,
                'model' => $item->model,
                'unit' => $item->unit,
                'color' => $item->color,
                'buy_date' => $item->buy_date,
                'supplier' => $item->supplier,
                'repair_cycle' => $item->repair_cycle,
                'enter_date' => $item->enter_date,
                'original_value' => $item->original_value,
                'loss_cycle' => $item->loss_cycle,
                'value_rate' => $item->value_rate,
                'clean_value' => $item->clean_value,
                'status' => $item->status,
                'take_date' => $item->take_date,
                'user_dept' => $item->user_dept,
                'user' => $item->user,
                'place' => $item->place,
                'remarks' => $item->remarks,
//                'spe' => $item->spe,
//                'model' => $item->model,
//                'unit' => $item->unit,
//                'number' => $item->number,
//                'price' => $item->price,
//                'total_value' => $item->total_value,
//                'pre_year' => $item->pre_year,
//                'pre_value' => $item->pre_value,
//                'buy_time' => $item->buy_time,
//                'use_person' => $item->use_person,
//                'depreciation_type' => $item->depreciation_type,
//                'depreciation_amount' => $item->depreciation_amount,
//                'depreciation_value' => $item->depreciation_value,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name : '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $find = FixedModel::where('name', $params['name'])->first();
        if($find){
            return $this->error('名称已存在');
        }

//        $startDate = Carbon::create(date('Y', strtotime($params['buy_date'])), date('m', strtotime($params['buy_date'])), date('d', strtotime($params['buy_date'])));
//        $endDate = Carbon::create(date('Y'), date('m'), date('d'));
//
//        // 计算两个时间之间的月份数
//        $monthsDifference = $startDate->diffInMonths($endDate);
//
//        if($monthsDifference > 1){
//            $depreciation_amount = round($params['total_value'] / ($params['pre_year'] * 12) * $monthsDifference, 2);
//        }else{
//            $depreciation_amount = 0;
//        }

//        $depreciation_value = round($params['total_value'] - $depreciation_amount, 2);




        $model = new FixedModel();
        $model->code = getCode('assets', "EML");
        $model->name = $params['name'];
        $model->category = $params['category'] ?? '';
        $model->type = $params['type'] ?? '';
        $model->spe = $params['spe'] ?? '';
        $model->model = $params['model'] ?? '';
        $model->color = $params['color'] ?? '';
        $model->unit = $params['unit'];
        $model->buy_date = $params['buy_date'];
        $model->supplier = $params['supplier'] ?? '';
        $model->repair_cycle = $params['repair'] ?? '';
        $model->enter_date = $params['enter_date'] ?? '';
        $model->original_value = $params['original_value'] ?? 0;
//        $model->loss_cycle = $params['loss_cycle'] ?? '';
        $model->value_rate = $params['value_rate'] ?? '';
        $model->pre_value = $params['pre_value'] ?? '';
        $model->pre_year = $params['pre_year'] ?? '';
        $model->clean_value = $params['clean_value'] ?? 0;
        $model->status = $params['status'] ?? '';
        $model->take_date =  $params['take_date'] ?? '';
        $model->user_dept = $params['user_dept'] ?? '';
        $model->user = $params['user'] ?? '';
        $model->place = $params['place'] ?? '';
        $model->remarks = $params['remarks'] ?? '';
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = FixedModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        if($model->name != $params['name']){
            $find = FixedModel::where('name', $params['name'])->first();
            if($find){
                return $this->error('名称已存在');
            }
        }

        $model->code = getCode('assets', "EML");
        $model->name = $params['name'];
        $model->category = $params['category'] ?? '';
        $model->type = $params['type'] ?? '';
        $model->model = $params['model'] ?? '';
        $model->unit = $params['unit'];
        $model->buy_date = $params['buy_date'];
        $model->supplier = $params['supplier'] ?? '';
        $model->repair_cycle = $params['repair'] ?? '';
        $model->enter_date = $params['enter_date'] ?? '';
        $model->original_value = $params['original_value'] ?? 0;
        $model->loss_cycle = $params['loss_cycle'] ?? '';
        $model->value_rate = $params['value_rate'] ?? '';
        $model->clean_value = $params['clean_value'] ?? 0;
        $model->status = $params['status'] ?? '';
        $model->take_date =  $params['take_date'] ?? '';
        $model->user_dept = $params['user_dept'] ?? '';
        $model->user = $params['user'] ?? '';
        $model->place = $params['place'] ?? '';
        $model->remarks = $params['remarks'] ?? '';
        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = FixedModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }

    public function delete_batch(Request $request){
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要删除的数据');
        }
        FixedModel::destroy($ids);
        return $this->success();
    }

    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = FixedModel::query();
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {


            $res = [
                'code' => $item->code,
                'name' => $item->name,
                'category' => $item->category,
                'spe' => $item->spe,
                'model' => $item->model,
                'unit' => $item->unit,
                'color' => $item->color,
                'buy_date' => $item->buy_date,
                'supplier' => $item->supplier,
                'repair_cycle' => $item->repair_cycle,
                'enter_date' => $item->enter_date,
                'pre_year' => $item->pre_year,
                'original_value' => $item->original_value,
                'value_rate' => $item->value_rate,
                'pre_value' => $item->pre_value,
                'end_date' => $item->end_date,
                'depreciation_month' => $item->depreciation_month,
                'depreciation_amount_month' => $item->depreciation_amount_month,
                'used_month' => $item->used_month,
                'depreciation_amount' => $item->depreciation_amount,
                'clean_value' => $item->clean_value,
                'status' => $item->status,
                'take_date' => $item->take_date,
                'user_dept' => $item->user_dept,
                'user' => $item->user,
                'place' => $item->place,
                'remarks' => $item->remarks,
            ];

            return $res;
        });

        $file_name = '固定资产-'.date('Ymd').'.xlsx';

        return Excel::download(new FixedExport($list), $file_name);
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file) {
            return $this->error('请选择文件');
        }

        $import = new FixedImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $staff = new FixedModel();
                foreach ($line as $k => $v){
                    $staff->$k = $v;
                }
                $staff->created_admin_id = $auth->id;
                $staff->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

}
